package top.haijunit.work.configurer;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.management.ManagementFactory;
import java.util.Date;
import java.util.Optional;

/**
 * 启动时执行
 *
 * @author zhanghaijun
 * @since 2024-08-07
 */
@Slf4j
@Order(1)
@Component
@RequiredArgsConstructor
public class ServerRunner implements ApplicationRunner {

    private final ApplicationContext ctx;

    @Override
    public void run(ApplicationArguments args) {
        String appJvmName = ManagementFactory.getRuntimeMXBean().getName();
        String path = Optional.ofNullable(ctx.getEnvironment().getProperty("server.servlet.context-path")).orElse("");
        String httpPort = ctx.getEnvironment().getProperty("server.port");
        String httpHost = ctx.getEnvironment().getProperty("project.plugin.ip-address");
        String httpUrl = "http://" + Optional.ofNullable(httpHost).orElse("127.0.0.1") + ":" + Optional.ofNullable(httpPort).orElse("8080") + path;
        String format = String.format("""

                         ========== 启动服务 ==========
                        \t 服务名称:\t%s
                        \t 进程ID: \t%s
                        \t 启动时间:\t%s
                        \t 访问路径:\t%s
                         ============================""",
                ctx.getEnvironment().getProperty("spring.application.name"),
                appJvmName.split("@")[0],
                DateUtil.format(new Date(ctx.getStartupDate()), DatePattern.NORM_DATETIME_MS_PATTERN),
                httpUrl);
        log.info("\033[1;33m {} \033[0m", format);
    }

    @PreDestroy
    public void destroy() {
        String format = String.format("""

                 ========== 暂停服务 ==========
                \t 服务名称：\t%s
                \t 暂停时间：\t%s
                ============================
                """, ctx.getEnvironment().getProperty("spring.application.name"), DateUtil.now());
        log.info("\033[1;33m {} \033[0m", format);
    }
}
